﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DXApplicationTangche.UC.客户CRM.Service;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DevExpress.Utils.Win;
using DXApplicationTangche.UC.销售记录.service;
using mendian;
using System.IO;
using DXApplicationTangche.UC.下单MTO.Service;

namespace DXApplicationTangche.UC.订单一览新.销售确认单
{
    public partial class Form积分抵扣 : DevExpress.XtraEditors.XtraForm
    {
        private String saleConfirmId;
        private Double price;
        private int confirmdScore;
        private ScoreAdjustJudgeVO scoreAdjustJudgeVO = new ScoreAdjustJudgeVO();

        public Form积分抵扣(String saleConfirmId, String mobile, Double price)
        {
            InitializeComponent();
            this.saleConfirmId = saleConfirmId;
            this.price = price;
            this.searchLookUpEdit店铺.Properties.DataSource = 销售记录Service.get店铺();
            this.searchLookUpEdit销售员.Properties.DataSource = 销售记录Service.get销售员();
            this.config读取店铺();
            //  查询客户现有积分
            int confirmdScore = CRM客户Service.getCustomerPWithIdentityAndScoreByMobile(mobile).confirmdScore;
            this.confirmdScore = confirmdScore;
            this.textBox客户现有积分.Text = confirmdScore.ToString();
            this.积分抵扣转化(confirmdScore / 100, price);
        }

        public void 积分抵扣转化(Double scorePrice, Double price)
        {
            //  金额对应积分为：
            int score = Convert.ToInt32(scorePrice * 100);
            //  1.兑换积分不能超越用户现有积分
            if (score > this.confirmdScore)
            {
                MessageBox.Show("兑换积分超过用户现有积分");
                this.积分抵扣转化(this.confirmdScore / 100, price);
                return;
            }
            else
            {
                //  2.兑换积分上限需要根据订单金额判断
                this.判断上限(scorePrice, price);
            }
        }

        private void 判断上限(Double scorePrice, Double price)
        {
            List<Double> priceList = new List<Double>();
            priceList.Add(scorePrice);
            priceList.Add(price);
            priceList.Sort();
            this.scoreAdjustJudgeVO.confirmdPrice = priceList.Min();
            this.textBox抵扣金额.Text = priceList.Min().ToString();
            this.textBox抵扣积分.Text = (priceList.Min() * 100).ToString();
        }

        private void textBox抵扣金额_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox抵扣金额.Text))
            {
                Double scorePrice;
                try { scorePrice = Convert.ToDouble(this.textBox抵扣金额.Text); } catch { scorePrice = 0.0; }
                this.积分抵扣转化(scorePrice, this.price);
            }
            else
            {
                this.textBox抵扣金额.Text = "";
                this.textBox抵扣积分.Text = "";
            }
        }
        #region 选择店铺
        private void searchLookUpEdit店铺_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear店铺Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit店铺View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit店铺.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.scoreAdjustJudgeVO.storeId = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.scoreAdjustJudgeVO.storeName = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                    if (!System.IO.File.Exists(@"xml\config店铺.xml"))
                    {
                        DealXML.ObjectToXMLFile(new DTO销售表头(this.scoreAdjustJudgeVO.storeId, this.scoreAdjustJudgeVO.storeName), @"xml\config店铺.xml", Encoding.UTF8);
                        this.config读取店铺();
                    }
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear店铺Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit店铺.ToolTip = null;
            searchLookUpEdit店铺.EditValue = null;
        }
        private void searchLookUpEdit店铺_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.scoreAdjustJudgeVO.storeName;
        }
        private void config读取店铺()
        {
            if (System.IO.File.Exists(@"xml\config店铺.xml"))
            {
                DTO销售表头 dTO店铺 = DealXML.XMLFlieToObject<DTO销售表头>(@"xml\config店铺.xml", Encoding.UTF8);
                this.scoreAdjustJudgeVO.buildStore(dTO店铺.id, dTO店铺.name);
                this.searchLookUpEdit店铺.Text = this.scoreAdjustJudgeVO.storeName;
                this.searchLookUpEdit店铺.Enabled = false;
            }
        }
        private void simpleButton重选店铺_Click(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(@"xml\config店铺.xml"))
            {
                File.Delete(@"xml\config店铺.xml");
                this.searchLookUpEdit店铺.Enabled = true;
                this.scoreAdjustJudgeVO.clearStore();
                this.searchLookUpEdit店铺.Text = "";
            }
        }
        #endregion
        #region 选销售员
        private void searchLookUpEdit销售员_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear销售员Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit销售员View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit销售员.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.scoreAdjustJudgeVO.assistantId = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.scoreAdjustJudgeVO.assistantName = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear销售员Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit销售员.ToolTip = null;
            searchLookUpEdit销售员.EditValue = null;
        }
        private void searchLookUpEdit销售员_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.scoreAdjustJudgeVO.assistantName;
        }
        #endregion
        private void simpleButton积分抵扣_Click(object sender, EventArgs e)
        {
            if (!this.scoreAdjustJudgeVO.build判空())
            {
                MessageBox.Show("请选择店铺、销售员");
                return;
            }
            if (this.scoreAdjustJudgeVO.confirmdPrice<=0)
            {
                MessageBox.Show("无可抵扣积分");
                return;
            }
            try
            {
                //  接口未调用
                PlainMessageResult plainMessageResult = 销售确认Service.saveSaleScoreAdjust(
                    new SaleAdjustDTO(
                        this.scoreAdjustJudgeVO.assistantId,
                        -this.scoreAdjustJudgeVO.confirmdPrice,
                        this.saleConfirmId,
                        this.richTextBox1.Text.Trim(),
                        this.scoreAdjustJudgeVO.storeId
                        )
                    );
                if (ConstPlainMessageResult.OK.Equals(plainMessageResult.errorCode))
                {
                    MessageBox.Show("抵扣成功");
                }
                else
                {
                    MessageBox.Show(plainMessageResult.errorMessage);
                }
                this.Close();
            }
            catch
            {
                MessageBox.Show("抵扣失败");
                this.Close();
            }
        }

    }

    public class ScoreAdjustJudgeVO
    {
        public Double confirmdPrice { get; set; }
        public String storeId { get; set; }
        public String storeName { get; set; }
        public String assistantId { get; set; }
        public String assistantName { get; set; }
        public ScoreAdjustJudgeVO buildStore(String storeId, String storeName)
        {
            this.storeId = storeId;
            this.storeName = storeName;
            return this;
        }
        public void clearStore()
        {
            this.storeId = "";
            this.storeName = "";
        }

        public Boolean build判空()
        {
            if (String.IsNullOrEmpty(this.storeId)
                || String.IsNullOrEmpty(this.assistantId))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}